package com.cheneyjoo.servlets;

import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.controller.StudentController;
import com.cheneyjoo.tools.AjaxJsonDataHelper;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@WebServlet(name = "StudentListServlet", urlPatterns = "/studentlist")
public class StudentListServlet extends HttpServlet {

    private static final long serialVersionUID = 1468219597144478175L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        JSONObject jsonObject = AjaxJsonDataHelper.getJsonObject(request);
        String no=jsonObject.get("no").toString();
        String name=jsonObject.get("name").toString();
        String sex=jsonObject.get("sex").toString();
        String rows=jsonObject.get("rows").toString();
        String page=jsonObject.get("page").toString();
        Map<String,String> where=new HashMap<>();
        if (Optional.ofNullable(no).isPresent()&&no.length()>0){
            where.put("no",no);
        }
        if (Optional.ofNullable(name).isPresent()&&name.length()>0){
            where.put("name",name);
        }
        if (Optional.ofNullable(sex).isPresent()&&sex.length()>0){
            where.put("sex",sex);
        }
        StudentController stu=new StudentController();
        Map<String, Object> students = stu.getStudents(where, Integer.parseInt(page), Integer.parseInt(rows));
        PrintWriter out = response.getWriter();
        out.print(new JSONObject(students));
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
